package server;

import game.Player;

import java.util.ArrayList;
import java.util.Random;

//public class PlayerManager {
//	private static PlayerManager instance;
public enum PlayerManager {
	INSTANCE;

	private ArrayList<Player> players;

	private PlayerManager() {
		this.players = new  ArrayList<Player>();
	}

	//	public static synchronized PlayerManager getInstance() {
	//		if(instance == null) instance = new PlayerManager();
	//		
	//		return instance;
	//	}

	public synchronized void addPlayer(Player player) {
		this.players.add(player);
	}

	public synchronized void removePlayer(Player player) {
		this.players.remove(player);
	}

	public synchronized int getPlayerCount() {
		return this.players.size();
	}

	public synchronized ArrayList<Player> getPlayers() {
		return new ArrayList<Player>(players);
	}

	public synchronized void update(Player player) {
		if (players.contains(player)) {
			Player currentPlayer = null;

			for (Player p : this.players) {
				if (p.equals(player)) {
					currentPlayer = p;
					break;
				}
			}

			if (player.getXpos()!=currentPlayer.getXpos() || player.getYpos()!=currentPlayer.getYpos()){
				if (isLegalMove(player)){
					System.out.println("Legal: "+player + "  " + currentPlayer);
					currentPlayer.setXpos(player.getXpos());
					currentPlayer.setYpos(player.getYpos());
					currentPlayer.addOnePoint();
				}
				else {
					System.out.println("Not legal: "+player + "  " + currentPlayer);
					currentPlayer.subOnePoint();
				}

			}

			currentPlayer.setDirection(player.getDirection());

		} else {
			this.players.add(player);

			String[][] map = game.GamePlayer.getMap();

			ArrayList<Integer[]> empty = new ArrayList<Integer[]>();

			for (int i = 0; i < map.length; i++) {
				for (int ii = 0; ii < map[i].length; ii++) {
					if (map[i][ii].equals("e")) {
						Integer[] pos = new Integer[2];
						pos[0] = ii;
						pos[1] = i;

						boolean occupied = false;
						for (Player p : this.players)
							if (p.getXpos() == ii && p.getYpos() == i)
								occupied = true;

						if (!occupied)
							empty.add(pos);
					}
				}
			}

			Random r = new Random();
			Integer[] randPos = empty.get(r.nextInt(empty.size()));

			player.setXpos(randPos[0]);
			player.setYpos(randPos[1]);
		}
	}


	private boolean isLegalMove(Player player) {
		String[][] map = game.GamePlayer.getMap();
		boolean legal = true;
		if(map[player.getXpos()][player.getYpos()].equals("w")){
			System.out.println("Hit wall");
			legal = false;
		}
		for (Player p: this.players){
			if (p.getXpos()==player.getXpos() && p.getYpos()==player.getYpos() && !p.equals(player)){
				legal = false;
				player.setPoint(player.getPoint()+50);
				p.setPoint(p.getPoint()-50);
			}
		}
		return legal;
	}

	public synchronized void printPlayers() {
		for (Player p : this.players)
			System.out.println("Name: " + p.getName() + ", x: " + p.getXpos()
					+ ", y: " + p.getYpos());
	}
}